package convert.converter;

import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

public class csv_to_xml {

    public static void main(String[] args) {
        String csvFilePath = "src/resource/csv/input_quoted_fields.csv";
        String xmlFilePath = "src/resource/xml/csv_output.xml";

        convertCSVToXML(csvFilePath, xmlFilePath);
    }

    public static void convertCSVToXML(String csvFilePath, String xmlFilePath) {
        try {
            CSVReader csvReader = new CSVReader(new FileReader(csvFilePath));
            List<String[]> dataList = csvReader.readAll();
            csvReader.close();

            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.newDocument();

            Element rootElement = document.createElement("data");
            document.appendChild(rootElement);

            for (String[] row : dataList) {
                Element rowElement = document.createElement("row");
                rootElement.appendChild(rowElement);

                for (int i = 0; i < row.length; i++) {
                    String columnName = "column" + (i + 1);
                    String columnValue = row[i];

                    Element columnElement = document.createElement(columnName);
                    columnElement.appendChild(document.createTextNode(columnValue));
                    rowElement.appendChild(columnElement);
                }
            }

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // 设置缩进和换行
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // 设置缩进的空格数

            DOMSource domSource = new DOMSource(document);
            StreamResult streamResult = new StreamResult(new File(xmlFilePath));
            transformer.transform(domSource, streamResult);

            System.out.println("CSV to XML conversion completed successfully.");
        } catch (IOException | ParserConfigurationException | javax.xml.transform.TransformerException e) {
            e.printStackTrace();
        } catch (CsvException e) {
            throw new RuntimeException(e);
        }
    }
}
